// packageRecruit/pages/create-details-info/create-details-info.js
import { establishWork,workDetailEcho,editWork } from '../../api/recruit'
import { toast,dateFormat } from '../../../utils/util'
import global from '../../../utils/global'
import user from '../../../utils/user'

Page({
    data: {
        workType:'0',
        workEndDate:'',
        jobBeginDay:'',// 工作开始日期
        workLabel:'',
        workLabelList:[{
            name:'日结',
            chosen:false
        },{
            name:'无尘服',
            chosen:false
        },{
            name:'保底工资',
            chosen:false
        },{
            name:'包住',
            chosen:false
        }],
        salaryTypeList: ['元/每时','元/每日','元/每周','元/每月'],
        salaryType:'元/每时',
        workBonus:'',
        workRecruitNum:'',
        workMoney:'',
        workEnrollType:'1',
        workEnrollNum:'',
        superiorInfo:{},
        files:[],
        workStartTime:'',
        workEndTime:'',
        again:{
            id:''
        },
        isAddLabel:false,
        addWorkLabel:'',
        endLimittTime:'',
        startLimittTime:'',
        isRecruitTips:false,
        recruitTipsTop:0,
        recruitTipsLeft:0,
        isBonusTips:false,
        bonusTipsTop:0,
        bonusTipsLeft:0
    },
    onLoad: function () {
        // options
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('createBasicInfo', (data)=>{
            console.log(data,'data')
            this.setData({
                superiorInfo:data
            })
            console.log(this.data.superiorInfo,'data')
        })
        setTimeout(()=>{
            if(this.data.superiorInfo.jobId){
                this.getWorkDetailEcho()
            }
        },200)
        
    },

    onReady: function () {
        let label = wx.getStorageSync('label')
        console.log(label,'label')
        if(!label){
            let workLabelList = ['日结','无尘服','保底工资','包住'].join(';')
            wx.setStorageSync('label',workLabelList)
        }
        label = wx.getStorageSync('label')
        let arr = []
        label.split(';').forEach((item)=>{
            arr.push({name:item,chosen:false})
        })
        this.setData({
            workLabelList:arr
        })
    },

    onShow: function () {

    },
    // 切换工作类型
    onWorkType(event){
        console.log(event,'event')
        this.setData({
            workType:event.currentTarget.dataset.type
        })
    },
    // 选择工作开始日期
    onWorkBeginDate(event){
        console.log(event.detail.value)
        const startTime = new Date((this.data.workEndDate || this.data.jobBeginDay) || dateFormat('YYYY-mm-dd',new Date())).getTime()
        const endTime = new Date(event.detail.value).getTime()
        let date1 = new Date(event.detail.value)
        let date2 = new Date(date1)
        date2.setDate(date1.getDate() + 30)
        this.setData({
            endLimittTime:date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate()
        })
        console.log(event.detail.value,this.data.jobBeginDay,this.data.workEndDate,'时间格式')
        console.log( endTime ,startTime,'num' )
        if(endTime > startTime){
            toast('开始日期不可大于结束日期！')
            return 
        }
        this.setData({
            jobBeginDay:event.detail.value
        })
    },
    // 选择工作结束日期
    onWorkEndDate(event){
        console.log(event,'event')
        const startTime = new Date(this.data.jobBeginDay || dateFormat('YYYY-mm-dd',new Date())).getTime()
        const endTime = new Date(event.detail.value).getTime()
        let date1 = new Date(event.detail.value)
        let date2 = new Date(date1)
        date2.setDate(date1.getDate() - 30)
        this.setData({
            startLimittTime:date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate()
        })
        if(startTime > endTime){
            toast('结束日期不可小于开始日期！')
            return 
        }
        this.setData({
            workEndDate:event.detail.value
        })
    },
    // 上班时间
    onWorkStartTime(event){
        this.setData({
            workStartTime:event.detail.value
        })
    },
    // 下班时间
    onWorkEndTime(event){
        this.setData({
            workEndTime:event.detail.value
        })
    },
    // 显示 添加标签弹框
    onAddPopup(){
        this.setData({
            isAddLabel:true
        })
    },
    cancel(){
        this.setData({
            isAddLabel:false
        })
    },
    // 添加 标签
    onAddLabel(){
        if(!this.data.addWorkLabel){
            toast('请输入内容！')
            return
        }
        // 新添加的标签不可和已存在的标签 一样
        let isRepeat = this.data.workLabelList.filter(item=>item.name == this.data.addWorkLabel)
        if(isRepeat.length > 0){
            toast('不可重复添加标签！')
            return
        }
        let workLabelList = ['日结','无尘服','保底工资','包住'].join(';')
        let splicing = (wx.getStorageSync('label') ? '' : workLabelList) + wx.getStorageSync('label') + (wx.getStorageSync('label') ? ';' : '') + this.data.addWorkLabel
        console.log(splicing,'splicing')
        wx.setStorageSync('label',splicing)
        let label = wx.getStorageSync('label')
        let arr = []
        label.split(';').forEach((item)=>{
            arr.push({name:item,chosen:false})
        })
        
        this.setData({
            isAddLabel:false,
            workLabelList:arr
        })
        
        console.log(this.data.workLabelList)
    },
    onSelectLabel(event){
        const { item,index } = event.currentTarget.dataset
        console.log(item,index,'event')
        // ['list[' + event.currentTarget.dataset.model + '].value']: event.detail.value
        this.setData({
            ['workLabelList[' + index + '].chosen']:!this.data.workLabelList[index].chosen
        })
        let arr =  this.data.workLabelList.filter(item=>item.chosen)
        console.log(arr,'arr')
        if(arr.length > 5){
            this.setData({
                ['workLabelList[' + index + '].chosen']:!this.data.workLabelList[index].chosen
            })
            toast('最多支持选择五个')
            return
        }
        console.log(this.data.workLabelList)
    },
    onWorkEnrollType(event){
        console.log(event,'event')
        this.setData({
            workEnrollType:event.currentTarget.dataset.type,
            workEnrollNum:event.currentTarget.dataset.type === '0' ? '' : this.data.workEnrollNum
        })
    },
    // 上一步
    onBack(){
        // wx.navigateBack()
        wx.redirectTo({
            url: '/packageRecruit/pages/create-basic-info/create-basic-info?type=edit&jobid=' + this.data.superiorInfo.jobId,
        })
    },
    async ontijiao(){
        // /[\u4e00-\u9fa5]/
        if(/[\D]/.test(this.data.workMoney)){
            toast('薪资仅支持输入数字')
            return
        }
        if(!this.data.workMoney){
            toast('请输入金额')
            return
        }
        if(!this.data.jobBeginDay){
            toast('请选择开始日期')
            return
        }
        if(!this.data.workEndDate){
            toast('请选择结束日期')
            return
        }
        if(!this.data.workStartTime){
            toast('请选择上班时间')
            return
        }
        if(!this.data.workEndTime){
            toast('请选择下班时间')
            return
        }
        // if(!this.data.workRecruitNum){
        //     toast('招聘人数至少输入一人')
        //     return
        // }
        // if((this.data.workEnrollNum < 1 || !this.data.workEnrollNum) && this.data.workEnrollType === '1'){
        //     toast('最低报名不可小于一天')
        //     return
        // }
        console.log(this.data.workLabelList,'workLabel')
        if(this.data.workLabelList.length < 1){
            toast('至少选择一个标签')
            return
        }
        let arr = []
        await this.data.workLabelList.forEach((item)=>{
            if(item.chosen){
                arr.push(item.name)
            }
        })
        await this.setData({
            workLabel:arr.join(';')
        })
        await this.uploadFile(this.data.superiorInfo.tempFile)
        console.log(this.data,'workEnrollNum')
    },
    // 创建岗位
    establishWorkPost(){
        console.log(this.data,'datadata')
        this.againAssignment()
        establishWork(this.data.again).then(async res=>{
            console.log(res,'res')
            await toast('创建成功')
            // wx.navigateBack({
            //     delta: 3
            // })
            wx.redirectTo({
                url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + res,
            })
        })
    },
    // 编辑岗位
    async setEditWork(){
        await this.againAssignment()
        console.log(this.data.again,'again')
        editWork(this.data.again).then(async ()=>{
            await toast('修改成功')
            // wx.navigateBack({
            //     delta: 3
            // })
            wx.redirectTo({
                url: '/packageRecruit/pages/work-job-detail/work-job-detail?jobid=' + this.data.superiorInfo.jobId,
            })
            // wx.navigateBack({
            //     delta: 2
            // })
        })
    },
    // 选择薪资类型
    onSalaryType(event){
        console.log(event.detail.value,'event')
        this.setData({
            salaryType:this.data.salaryTypeList[(Number(event.detail.value))]
        })
    },
    // 提示 招聘文字
    onRecruitTips(){
        const query = wx.createSelectorQuery()
        query.select('#recruit').boundingClientRect()
        query.exec((res) => {
            console.log(res,'top') // 这个节点距离顶部的距离   和距离底部的距离
            this.setData({
                isRecruitTips:true,
                recruitTipsTop: res[0].top + 4,
                recruitTipsLeft: 188
            })
        })
    },
    cancelTipInsurance(){
        if(this.data.isRecruitTips){
            this.setData({
                isRecruitTips:false
            }) 
            return
        }

        if(this.data.isBonusTips){
            this.setData({
                isBonusTips:false
            })
            return
        }
    },
    // 提示成团奖文字
    onBonusTips(){
        const query = wx.createSelectorQuery()
        query.select('#bonus').boundingClientRect()
        query.exec((res) => {
            console.log(res,'top') // 这个节点距离顶部的距离   和距离底部的距离
            this.setData({
                isBonusTips:true,
                bonusTipsTop: res[0].top + 4,
                bonusTipsLeft: 188
            })
        })
    },
    // 文件批量上传
    async uploadFile(tempFiles) {
        console.log(tempFiles,'tempFiles上传的文件')
        const t =this
        const uploadedFile = []
        const notUploaded = []
        tempFiles.forEach(item=>{
            if(item.tempFilePath){
                notUploaded.push(item)
            }else{
                uploadedFile.push(item)
            }
        })
        console.log(uploadedFile,notUploaded)
        wx.showLoading({
            title: '文件上传中',
            mask: true
        })
        let promise = Promise.all(notUploaded.map((item)=>{
            return new Promise((resolve)=>{
                wx.uploadFile({
                    url:global.baseUrl + global.zpUrl + '/api/v2/zp/job/upload-file',
                    filePath:item.tempFilePath,
                    name:'file',
                    header:{'Authorization': 'Wx ' + global.token},
                    success(res){
                        console.log('上传成功',res.data)
                        resolve(res.data)
                    },
                    fail(rej){
                        console.log(rej,'rej')
                    }
                })
            })
        }))
        promise.then(async res=>{
            console.log(res,'resresres')
            const files = []
            await res.forEach(item=>{
                const url = JSON.parse(item).data.fileUrl
                const size = JSON.parse(item).data.fileSize
                let type = 'photo'
                if (
                    /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(url.toLowerCase())
                ) {
                    console.log(type)
                    type = 'video'
                }
                files.push({fileUrl:url,fileType:type,fileSize:size})
                console.log('提交成功0')
                
            })
            uploadedFile.push(...files) 
            await t.setData({
                files:uploadedFile
            })
            console.log(uploadedFile,'uploadedFile')
            console.log(this.data.files,'files')
            wx.hideLoading()
            if(!this.data.superiorInfo.jobId){
                console.log('创建')
                await this.establishWorkPost()
            }else{
                console.log('编辑')
                await this.setEditWork()
            }
            
        })
    },
    // 信息回显
    getWorkDetailEcho(){
        workDetailEcho({
            jobId:this.data.superiorInfo.jobId
        }).then(res=>{
            console.log(res,'res')
            
            const arrTag = res.jobTag.split(';')
            const workLabelListClone = JSON.parse(JSON.stringify(this.data.workLabelList))
            workLabelListClone.forEach((item,index)=>{
                arrTag.forEach((ite)=>{
                    if(item.name === ite){
                        this.data.workLabelList[index].chosen = true
                    }
                })
            })
            console.log(this.data.workLabelList,'workLabelList')
            this.setData({
                workType:res.workType,
                workEndDate:res.jobEndDay,
                jobBeginDay:res.jobBeginDay,
                workLabel:res.jobTag,
                workBonus:res.teamAward,
                workRecruitNum:res.headCount,
                workMoney:res.salary,
                workEnrollType:res.applyDays ? res.applyDays : 0,
                workEnrollNum:res.applyDays || '',
                workStartTime:res.jobSignRule.split('-')[0],
                workEndTime:res.jobSignRule.split('-')[1],
                workLabelList:this.data.workLabelList,
                salaryType:res.jobSalaryType
            })
        })
    },
    againAssignment(){
        this.setData({
            ['again.id']:this.data.superiorInfo.jobId,
            ['again.serialNumber']:(user.userId + '' + new Date().getTime()),
            ['again.jobName']:this.data.superiorInfo.workName,
            ['again.classifyId']:this.data.superiorInfo.hostId + ',' + this.data.superiorInfo.childrenId,
            ['again.serveCompanyName']:this.data.superiorInfo.serveCompanyName,
            ['again.jobAddress']:this.data.superiorInfo.workAddress,
            ['again.city']:this.data.superiorInfo.city,
            ['again.district']:this.data.superiorInfo.district,
            ['again.serveCompanyId']:this.data.superiorInfo.serveCompanyId,
            ['again.jobDetail']:this.data.superiorInfo.template,
            ['again.jobLocation']:this.data.superiorInfo.workLongitude + ',' + this.data.superiorInfo.workLatitude,
            ['again.workType']:this.data.workType,
            ['again.jobSalaryType']:this.data.salaryType,
            ['again.salary']:this.data.workMoney,
            ['again.jobBeginDay']:this.data.jobBeginDay,// 工作开始日期 dateFormat('YYYY-mm-dd',new Date())
            ['again.jobEndDay']:this.data.workEndDate,// 工作结束日期
            ['again.jobSignRule']:this.data.workStartTime + '-' + this.data.workEndTime,// 上班时间下班时间
            ['again.jobTag']:this.data.workLabel,// 标签
            ['again.headCount']:this.data.workRecruitNum,
            ['again.teamAward']:this.data.workBonus,
            ['again.applyDays']:this.data.workEnrollType == '0' ? this.data.workEnrollType : this.data.workEnrollNum,
            ['again.params.photos']:this.data.files
        })
    }
})